package bmt.audioplayer.app;

import android.app.ActionBar;
import android.app.SearchManager;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.TypefaceSpan;
import android.transition.Visibility;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.SeekBar;
import android.widget.TextView;

import java.io.IOException;

import bmt.audioplayer.app.anim.player.DepthPageTranformer;
import bmt.audioplayer.app.controller.player.PlayerController;
import bmt.audioplayer.app.fragment.player.PlayerMainFragment;
import bmt.audioplayer.app.fragment.player.PlayerPlaylistFragment;
import bmt.audioplayer.app.model.player.Song;
import bmt.audioplayer.app.util.ImageHelper;
import bmt.audioplayer.app.util.KeyProvider;
import bmt.audioplayer.app.util.Util;

public class PlayerActivity extends FragmentActivity {

    private ImageButton btnPlay, btnNext, btnPre, btnRepeat, btnShuff;
    private SeekBar songSeekBar;
    private TextView totalDuration;
    private RelativeLayout playerControlView;
    private RelativeLayout playerMainView;

    MediaPlayer mediaPlayer;
    ViewPager viewPager;
    PlayerMainFragment playerMainFragment;
    PlayerPlaylistFragment playerPlaylistFragment;

    ActionBar actionBar;
    PlayerController playerController;
    float beginDegree = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);

        actionBar = Util.setupActionBar(this, getActionBar(), getResources().getString(R.string.player_actionbar_default));
        /*TODO */
        TypedValue tv = new TypedValue();
        if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            KeyProvider.ACTIONBAR_HEIGHT = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
        }

        playerController = new PlayerController(this);

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(playerController);

        setContentView(R.layout.cat_player);
        /*-- Pager --*/
        viewPager = (ViewPager) findViewById(R.id.playerPager);
        viewPager.setAdapter(playerController.getPlayerPagerAdapter());
        viewPager.setCurrentItem(0);

        playerMainView = (RelativeLayout) findViewById(R.id.player_main);
        playerControlView = (RelativeLayout) findViewById(R.id.player_control);

        playerPlaylistFragment = PlayerPlaylistFragment.create();
        playerMainFragment = PlayerMainFragment.create();

        /*-- Set up element --*/
        btnPlay = (ImageButton) findViewById(R.id.player_btn_play);
        btnPlay.setOnClickListener(playerController);

        btnNext = (ImageButton) findViewById(R.id.player_btn_next);
        btnNext.setOnClickListener(playerController);

        btnPre = (ImageButton) findViewById(R.id.player_btn_pre);
        btnPre.setOnClickListener(playerController);

        btnRepeat = (ImageButton) findViewById(R.id.player_btn_repeat);
        btnRepeat.setOnClickListener(playerController);

        btnShuff = (ImageButton) findViewById(R.id.player_btn_shuff);
        btnShuff.setOnClickListener(playerController);

        totalDuration = (TextView) findViewById(R.id.player_song_duration);

        songSeekBar = (SeekBar) findViewById(R.id.player_song_seek);
        songSeekBar.setOnSeekBarChangeListener(playerController);

    }

    public void playSong(Song song) {
        try {
            String path = song.getPath();
            mediaPlayer.reset();
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            long duration = mediaPlayer.getDuration();
            String durationTime = playerController.miliSecondsToTimer(duration);
            actionBar.setTitle(Util.getSpannableActionBar(this,song.getName()));
            actionBar.setSubtitle(Util.getSpannableActionBar(this,song.getArtist()));
            btnPlay.setImageResource(R.drawable.btn_pause);
            songSeekBar.setProgress(0);
            songSeekBar.setMax(100);
            totalDuration.setText(durationTime);
            mediaPlayer.start();
            playerController.updateProgress();
            updatePlayerFragment();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void restartLineAnimation() {
        if (playerMainFragment.isVisible()) {
            playerMainFragment.setupLineAnimation(playerController.getTimeLeft(), mediaPlayer.isPlaying());
        }
    }

    public void pauseLineAnimation() {
        if (playerMainFragment.isVisible()) {
            playerMainFragment.pauseLineAnimation();
        }
    }

    public void onTogglePlayMode() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                pauseLineAnimation();
                btnPlay.setImageResource(R.drawable.btn_play);
            } else {
                mediaPlayer.start();
                restartLineAnimation();
                btnPlay.setImageResource(R.drawable.btn_pause);
            }
        }
    }

    public void settingSelectedItemView(View rowSelect) {
        playerPlaylistFragment.settingSelectedItemView(rowSelect);
    }

    public void updatePlayerFragment() {
        if (playerMainFragment.isVisible()) {
            playerMainFragment.setPictureSong(playerController.getSongPicture());
            playerMainFragment.setupLineAnimation(playerController.getTimeLeft(), mediaPlayer.isPlaying());
            playerMainFragment.setRemindText(playerController.isFirstTime());
            playerMainFragment.setCatImage(playerController.isFirstTime());
        }
    }

    public void updatePlaylistFragment(){
        if (playerPlaylistFragment.isVisible()) {
            playerPlaylistFragment.refreshItemList();
        }
    }

    public Fragment setupPlayerPage(int position) {
        if (position == 1) {
            updatePlayerFragment();
            /*-- Set parameter for the fist time --*/
            Bundle args = new Bundle();
            args.putByteArray(KeyProvider.PLAYER_SONG_IMG, playerController.getSongPicture());
            args.putLong(KeyProvider.PLAYER_SONG_DURATION, playerController.getTimeLeft());
            args.putBoolean(KeyProvider.PLAYER_SONG_ISPLAY, mediaPlayer.isPlaying());
            playerMainFragment.setArguments(args);
            return playerMainFragment;
        } else if (position == 0) {
            return playerPlaylistFragment;
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        playerController.clearRunTime();
        mediaPlayer.stop();
        mediaPlayer.reset();
        mediaPlayer.release();
        mediaPlayer = null;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater =  getMenuInflater();
        inflater.inflate(R.menu.player, menu);

        SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView)menu.findItem(R.id.player_search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(false);
        searchView.setOnQueryTextListener(playerController);
        searchView.setOnCloseListener(playerController);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        return id == R.id.action_settings || super.onOptionsItemSelected(item);
    }

    public TextView getTotalDuration() {
        return totalDuration;
    }

    public SeekBar getSongSeekBar() {
        return songSeekBar;
    }


    public ImageButton getBtnRepeat() {
        return btnRepeat;
    }

    public ImageButton getBtnShuff() {
        return btnShuff;
    }

    public MediaPlayer getMediaPlayer() {
        return mediaPlayer;
    }

    public PlayerController getPlayerController() {
        return playerController;
    }

    public void setPlayerController(PlayerController playerController) {
        this.playerController = playerController;
    }

    public void showPlayerControl() {
        if (playerControlView.getVisibility() == View.INVISIBLE) {
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) playerMainView.getLayoutParams();
            layoutParams.height = 0;
            layoutParams.weight = 0.75f;
            playerMainView.setLayoutParams(layoutParams);
            playerControlView.setVisibility(View.VISIBLE);
        }
    }
}
